package com.typy.www.tpay.ui.acitivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.typy.www.tpay.R;
import com.typy.www.tpay.base.BaseBackActivity;
import com.typy.www.tpay.bean.bean.BaseReturn;
import com.typy.www.tpay.bean.listvm.ActivicationListVm;
import com.typy.www.tpay.bean.listvm.BuyCenterListVm;
import com.typy.www.tpay.bean.listvm.BuyConfigListVm;
import com.typy.www.tpay.bean.vm.ActivicationVm;
import com.typy.www.tpay.bean.vm.BuyCenterVm;
import com.typy.www.tpay.bean.vm.BuyConfigVm;
import com.typy.www.tpay.bean.vm.BuyVm;
import com.typy.www.tpay.bean.vm.RedMoneyVm;
import com.typy.www.tpay.constance.Constance;
import com.typy.www.tpay.constance.MessageEvent;
import com.typy.www.tpay.ui.adapter.IcotypeAdapter;
import com.typy.www.tpay.ui.adapter.RadioAdapter;
import com.typy.www.tpay.ui.adapter.RecordAdapter;
import com.typy.www.tpay.ui.dialog.SyDialogHelper;
import com.typy.www.tpay.ui.dialog.SyMessageDialog;
import com.typy.www.tpay.ui.prt.PtrListContent;
import com.typy.www.tpay.ui.view.XRadioGroup;
import com.typy.www.tpay.ui.view.dialog.BuyInDialog;
import com.typy.www.tpay.ui.view.dialog.RedEnvelopeDialog;
import com.typy.www.tpay.util.ClassHoldUtil;
import com.typy.www.tpay.util.GsonUtils;
import com.typy.www.tpay.util.Logutil;
import com.typy.www.tpay.util.MessageAction;
import com.typy.www.tpay.util.ParamsUtil;
import com.typy.www.tpay.util.PwdDailogUtil;
import com.typy.www.tpay.util.ScollGridView;
import com.typy.www.tpay.util.StringUtil;
import com.typy.www.tpay.util.ToastUtil;
import com.typy.www.tpay.util.UiHelper;
import com.typy.www.tpay.util.UpdataUiUtil;
import com.typy.www.tpay.util.inter.InputCallBack;
import com.typy.www.tpay.util.listviewanimations.IntentUtil;
import com.typy.www.tpay.volley.HTTPUtils;
import com.typy.www.tpay.volley.VolleyListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by 13799 on 2018/7/27.
 */

public class BuyCenterActivity extends BaseBackActivity {

    @BindView(R.id.rg_root2)
    XRadioGroup rgRoot2;
    @BindView(R.id.ll_headWeiwancheng)
    LinearLayout llHeadWeiwancheng;
    @BindView(R.id.ll_buycenter_head)
    LinearLayout llBuycenterHead;
    @BindView(R.id.rg_1)
    XRadioGroup rg1;
    @BindView(R.id.rb1)
    RadioButton rb1;
    @BindView(R.id.rb2)
    RadioButton rb2;
    @BindView(R.id.gv_mine)
    ScollGridView gvMine;
    private RadioAdapter radioAdapter;
    private int classType;
    private PtrListContent ptrListContent;
    private List<BuyVm> buydatas = new ArrayList<>();
    private List<ActivicationVm> mData = new ArrayList<>();
    private ListView mListView;
    private String fdAmountConfigId;
    private RecordAdapter recordAdapter;
    private RecordAdapter recordAdapter2;
    private ActivicationListVm mListVm;

    private BuyConfigListVm buyConfigListVm;
    private List<BuyConfigVm> configData;
    private BuyConfigVm buyConfigVm;
    private BuyInDialog mBuyInDialog;
    private Activity mActivity = this;
    private View headView2;
    private boolean isFirst=true;




    public static void show(Context context, int classType) {
        Intent intent = new Intent();
        intent.putExtra("classType", classType);
        IntentUtil.intent2Activity(context, intent, BuyCenterActivity.class);

    }

    public static void show(Context context, int classType, String fdAmountConfigId) {
        Intent intent = new Intent();
        intent.putExtra("classType", classType);
        intent.putExtra("fdAmountConfigId", fdAmountConfigId);
        IntentUtil.intent2Activity(context, intent, BuyCenterActivity.class);

    }

    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        classType = getIntent().getIntExtra("classType", 0);
        fdAmountConfigId = getIntent().getStringExtra("fdAmountConfigId");
        initTitle();
        initAdapter();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(final MessageEvent msg) {
        if (msg.getKey().equals(MessageAction.BUYCANCELORDER)) {
            PwdDailogUtil.show(this, new InputCallBack() {
                @Override
                public void onInputFinish(String result) {
                    cancelOrder(msg.getMessage(), result);
                }
            });
        } else if (msg.getKey().equals(MessageAction.BUYCENTERDAILOG)) {
            int position = msg.getMessage4();
            showBuyInDailog(mData.get(position));
        } else if (msg.getKey().equals(MessageAction.REFRESHWEIWANCHENG)) {
            getNoselectpaylistData(1, true);
        }else if(msg.getKey().equals(MessageAction.REFEFRESHTOUSU)){
            getNoselectpaylistData(1, true);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(isFirst){
            isFirst=false;
        }else if (classType != ClassHoldUtil.BUYINCENTER &&classType != ClassHoldUtil.SELLOUTCENTER) {
            UiHelper.showLoading(getActivity());
            getNoselectpaylistData(1, true);
        }
    }

    @Override
    protected void onDestroy() {
        if (mBuyInDialog != null)
            mBuyInDialog.dismiss();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }



    private void initAdapter() {

        radioAdapter.setListener(new RadioAdapter.BuyConfigListener() {
            @Override
            public void getBuyConfig(BuyConfigVm vm) {
                buyConfigVm = vm;
                getData(1, true);
            }
        });
        if (classType == ClassHoldUtil.BUYWEIWANCHENG || classType == ClassHoldUtil.SELLWEIWANCHENG
                || classType == ClassHoldUtil.BUYWEIWANCHENGC || classType == ClassHoldUtil.SELLWEIWANCHENGC)
            getNoselectpaylistData(1, true);
        gvMine.setAdapter(radioAdapter);
        mListView.setAdapter(recordAdapter);

    }

    private void initTitle() {
        setTitle(ClassHoldUtil.getClassTitle(classType));
        recordAdapter = new RecordAdapter(getActivity());
        recordAdapter.setClassType(classType);
        recordAdapter2 = new RecordAdapter(getActivity());
        radioAdapter = new RadioAdapter(getActivity());
        if (classType == ClassHoldUtil.BUYINCENTER || classType == ClassHoldUtil.SELLOUTCENTER) {
            ((TextView) mBtnRight).setText("记录");
            mBtnRight.setVisibility(View.VISIBLE);
            llHeadWeiwancheng.setVisibility(View.GONE);
            llBuycenterHead.setVisibility(View.VISIBLE);
            getAmountitemlistData();

        } else {
            mBtnRight.setVisibility(View.GONE);
            llHeadWeiwancheng.setVisibility(View.VISIBLE);
            llBuycenterHead.setVisibility(View.GONE);
            if(classType == ClassHoldUtil.SELLWEIWANCHENGC||classType == ClassHoldUtil.SELLWEIWANCHENG){
                rb1.setText("未选择打款人");
                rb2.setText("已选择打款人");
            }else{
                rb1.setText("未选择收款人");
                rb2.setText("已选择收款人");
            }

            if (classType == ClassHoldUtil.SELLWEIWANCHENGC || classType == ClassHoldUtil.BUYWEIWANCHENGC) {
                rb2.setChecked(true);
                updateRb(rb2);
                setClassType();
            }
        }
        rg1.setOnCheckedChangeListener(new XRadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(XRadioGroup group, int checkedId) {
                if (checkedId == rb1.getId()) {
                    updateRb(rb1);
                } else if (checkedId == rb2.getId()) {
                    updateRb(rb2);
                }
                setClassType();
                getNoselectpaylistData(1, true);
            }
        });

    }

    @Override
    protected View getContentView() {
        LinearLayout linearLayout = new LinearLayout(getActivity());
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        View headView = LayoutInflater.from(getActivity()).inflate(R.layout.activity_buy_center, null);
        linearLayout.addView(headView);
        headView2 = LayoutInflater.from(getActivity()).inflate(R.layout.head_record, null);
        headView2.findViewById(R.id.img_div).setVisibility(View.VISIBLE);
        UpdataUiUtil.getDefaul().setText("卖出余额", (TextView) headView2.findViewById(R.id.tv_type))
                .setText("创建时间", (TextView) headView2.findViewById(R.id.tv_amount))
                .setText("操作", (TextView) headView2.findViewById(R.id.tv_time));
        linearLayout.addView(headView2);
        ptrListContent = new PtrListContent(getActivity()) {
            @Override
            protected void getPage(int pageIndex, boolean refresh) {
                if (classType == ClassHoldUtil.BUYINCENTER || classType == ClassHoldUtil.SELLOUTCENTER) {
                    getData(pageIndex, refresh);
                } else {
                    getNoselectpaylistData(pageIndex, refresh);
                }
            }
        };
        mListView = ptrListContent.getListView();
        linearLayout.addView(ptrListContent.getmView());
        return linearLayout;
    }

    //设置adapter
    private void setClassType() {
        Logutil.print("classType==" + classType);
        if (classType == ClassHoldUtil.SELLWEIWANCHENG || classType == ClassHoldUtil.SELLWEIWANCHENGC) {
            if (rb1.isChecked()) {
                classType = ClassHoldUtil.SELLWEIWANCHENG;
                headView2.setVisibility(View.VISIBLE);
                recordAdapter.setClassType(classType);
                mListView.setAdapter(recordAdapter);
            } else {
                classType = ClassHoldUtil.SELLWEIWANCHENGC;
                headView2.setVisibility(View.GONE);
                recordAdapter2.setClassType(classType);
                mListView.setAdapter(recordAdapter2);
            }
        } else {
            if (rb1.isChecked()) {
                classType = ClassHoldUtil.BUYWEIWANCHENG;
                headView2.setVisibility(View.VISIBLE);
                mListView.setAdapter(recordAdapter);
                recordAdapter.setClassType(classType);
            } else {
                classType = ClassHoldUtil.BUYWEIWANCHENGC;
                headView2.setVisibility(View.GONE);
                recordAdapter2.setClassType(classType);
                mListView.setAdapter(recordAdapter2);
            }
        }
        Logutil.print("classType==" + classType);
    }

    private void updateRb(TextView textView) {
        rb1.setTextColor(getResources().getColor(R.color.text_darkcolor));
        rb2.setTextColor(getResources().getColor(R.color.text_darkcolor));
        textView.setTextColor(getResources().getColor(R.color.blue67BCFD));
    }


    @Override
    protected void onRightButtonClick() {
        super.onRightButtonClick();
        if (classType == ClassHoldUtil.BUYINCENTER)
            RecordActivity.show(getActivity(), ClassHoldUtil.BUYINCORECORD);
        else
            RecordActivity.show(getActivity(), ClassHoldUtil.SELLOUTRECORD);

    }


    //获取数据
    private void getData(final int page, final boolean refresh) {
        ParamsUtil params = new ParamsUtil();
        params.put("pageNum", page);
        params.put("pageSize", Constance.LIMT);
        params.put("fdAmountConfigId", buyConfigVm.getFdAmountConfigId());
        String url = "";
        if (classType == ClassHoldUtil.BUYINCENTER)
            url = Constance.getBuycenterURL();
        else
            url = Constance.getSellercenterURL();
        HTTPUtils.post(getActivity(), url, params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                UiHelper.hideLoading();
                if (ret.getCode() == 200 && ret.getData() != null) {
                    if (refresh || page == 1) {
                        mData.clear();
                        recordAdapter.notifyDataSetChanged();
                    }
                    mListVm = GsonUtils.parseJSON(ret.getData().toString(), ActivicationListVm.class);
                    if (mListVm != null && mListVm.getData() != null && mListVm.getData().size() != 0) {
                        mData.addAll(mListVm.getData());
                        recordAdapter.setData(mData);
                        recordAdapter.notifyDataSetChanged();

                    }
                    ptrListContent.loadInitialPage(mListView.getCount());
                } else {
                    ptrListContent.loadInitialPage(0);
                }
            }

            @Override
            public void onResponseErr(int code, String msg) {
                ptrListContent.loadInitialPage(0);
            }
        });
    }

    //获取未完成数据
    private void getNoselectpaylistData(final int page, final boolean refresh) {
        ParamsUtil params = new ParamsUtil();
        String url = "";
        params.put("pageNum", page);
        params.put("pageSize", Constance.LIMT);
        if(refresh){
            mData.clear();
            recordAdapter2.notifyDataSetChanged();
            recordAdapter.notifyDataSetChanged();
        }

        if (classType == ClassHoldUtil.SELLWEIWANCHENG) {
            url = Constance.getNoselectpaylistURL();
        } else if (classType == ClassHoldUtil.SELLWEIWANCHENGC) {
            url = Constance.getSelectpaylistURL();
        } else if (classType == ClassHoldUtil.BUYWEIWANCHENG) {
            url = Constance.getNoselectreceivelistURL();
        } else if (classType == ClassHoldUtil.BUYWEIWANCHENGC) {
            url = Constance.getSelectreceivelistURL();
        }
        HTTPUtils.post(getActivity(), url, params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                UiHelper.hideLoading();
                if (ret.getCode() == 200 && ret.getData() != null) {
                    if (refresh || page == 1) {
                        mData.clear();
                        recordAdapter.notifyDataSetChanged();
                    }
                    mListVm = GsonUtils.parseJSON(ret.getData().toString(), ActivicationListVm.class);
                    if (mListVm != null && mListVm.getData() != null && mListVm.getData().size() != 0) {
                        mData.addAll(mListVm.getData());
                        recordAdapter.setData(mData);
                        recordAdapter.notifyDataSetChanged();
                        recordAdapter2.setData(mData);
                        recordAdapter2.notifyDataSetChanged();
                    }
                }
                ptrListContent.loadInitialPage(mListVm.getCount());
            }

            @Override
            public void onResponseErr(int code, String msg) {
                ptrListContent.loadInitialPage(0);
            }
        });
    }

    private void getAmountitemlistData() {
        ParamsUtil params = new ParamsUtil();
        HTTPUtils.post(getActivity(), Constance.getAmountitemlistURL(), params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                if (ret != null && ret.getData() != null) {
                    buyConfigListVm = GsonUtils.parseJSON(ret.getData().toString(), BuyConfigListVm.class);
                    if (buyConfigListVm != null && buyConfigListVm.getData() != null && buyConfigListVm.getData().size() > 0) {
                        configData = buyConfigListVm.getData();
                        for (int i = 0; i < configData.size(); i++) {
                            if (configData.get(i).getFdAmountConfigId().equals(fdAmountConfigId)) {
                                configData.get(i).setCheck(true);
                                buyConfigVm = configData.get(i);
                            }
                        }
                        radioAdapter.setBuyConfigList(configData);
                        radioAdapter.notifyDataSetChanged();
                    }
                    getData(1, true);
                }
            }

            @Override
            public void onResponseErr(int code, String msg) {
                ptrListContent.loadInitialPage();
            }
        });
    }

    //取消订单
    private void cancelOrder(String fdOrderId, String pwd) {
        ParamsUtil paramsUtil = new ParamsUtil();
        paramsUtil.put("fdOrderId", fdOrderId);
        paramsUtil.putMd5("fdPayPwd", pwd);
        String url = "";
        if (classType == ClassHoldUtil.BUYWEIWANCHENG) {
            if (rb1.isChecked()) {
                url = Constance.getCancelbuynoselectURL();
            } else {
                url = Constance.getCancelbuyselectURL();
            }
        } else if (classType == ClassHoldUtil.SELLWEIWANCHENG) {
            if (rb1.isChecked()) {
                url = Constance.getCancelsellernoselectURL();
            }
        }
        HTTPUtils.post(getActivity(), url, paramsUtil.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                PwdDailogUtil.hide();
                ToastUtil.getInstance().show("成功取消订单");
                getNoselectpaylistData(1, true);
            }

            @Override
            public void onResponseErr(int code, String msg) {
                if (!Constance.WRONGPWD.equals(msg))
                    PwdDailogUtil.hide();
                UiHelper.showToast(getActivity(), msg);

            }
        });
    }

    //购买
    private void creatOrder(String fdOrderId, String pwd) {
        ParamsUtil paramsUtil = new ParamsUtil();
        paramsUtil.put("fdOrderId", fdOrderId);
        paramsUtil.putMd5("fdPayPwd", pwd);
        String url = "";
        if (classType == ClassHoldUtil.BUYINCENTER) {
            url = Constance.getBuyURL();
        } else {
            url = Constance.getSellersellerURL();
        }

        HTTPUtils.post(getActivity(), url, paramsUtil.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                PwdDailogUtil.hide();
                getData(1, true);
                SyDialogHelper.showDlg(getActivity(), "提示", "订单创建成功", "确定", new SyMessageDialog.OnClickListener() {
                    @Override
                    public void onClick(SyMessageDialog dialog) {
                        if (classType == ClassHoldUtil.BUYINCENTER)
                            BuyCenterActivity.show(getActivity(), ClassHoldUtil.BUYWEIWANCHENGC);
                        else
                            BuyCenterActivity.show(getActivity(), ClassHoldUtil.SELLWEIWANCHENGC);
                    }
                });

            }

            @Override
            public void onResponseErr(int code, String msg) {
                if (!Constance.WRONGPWD.equals(msg))
                    PwdDailogUtil.hide();
                UiHelper.showToast(getActivity(), msg);

            }
        });
    }

    //显示弹窗
    private void showBuyInDailog(final ActivicationVm vm) {

        if (vm == null) {
            return;
        }

        if (mBuyInDialog == null) {
            mBuyInDialog = new BuyInDialog(getActivity(), R.style.WarningDialog);
        }
        mBuyInDialog.setListener(new BuyInDialog.OnDismantlingListener() {
            @Override
            public void onDismantlingRespon(int type) {
                if (mBuyInDialog != null) {
                    mBuyInDialog.dismiss();
                }
                PwdDailogUtil.show((FragmentActivity) mActivity, new InputCallBack() {
                    @Override
                    public void onInputFinish(String result) {
                        creatOrder(vm.getFdOrderId(), result);
                    }
                });
            }
        });
        mBuyInDialog.updataView(vm, classType);
        mBuyInDialog.show();
    }

}
